﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using SelfService.Model;
using SelfService.Model.Interface;
using SelfService.Model.Models;
using WalkingTec.Mvvm.Core;


namespace SelfService.Tasks
{
    [Display(Name = "退款结果查询")]
    public class RefundTask : BaseTask
    {
        private readonly IServiceProvider _provider;
        public RefundTask(WTMContext context, IServiceProvider provider) : base(context)
        {
            _provider = provider;
        }

        public override async Task<bool> Process()
        {
            this.Logger("查询退款结果", ActionLogTypesEnum.Debug);
            try
            {
                //调用支付接口
                IPaySystem service;
                try
                {
                    var scope = _provider.CreateScope();
                    service = scope.ServiceProvider.GetService<IPaySystem>();
                }
                catch (Exception)
                {
                    this.Logger($"没有启用支付服务", ActionLogTypesEnum.Exception);
                    return false;
                }
                if (service == null)
                {
                    this.Logger($"没有启用支付服务", ActionLogTypesEnum.Exception);
                    return false;
                }

                var dc = Context.DC;
                var list = await dc.Set<SysPay>()
                    .Where(e => e.PayStatus == PayStatusEnum.支付成功 && e.RefundStatus == RefundStatusEnum.退款中)
                    .ToListAsync();
                foreach (var element in list)
                {
                    var result = await service.CheckRefund(element);
                    if (result.Code == 200)
                    {
                        element.RefundNo = result.Data.RefundNo;
                        element.RefundStatus = RefundStatusEnum.退款完成;
                        element.UpdateTime = DateTime.Now;
                        this.Logger($"订单[{element.OutOrderNo}]退款成功", ActionLogTypesEnum.Debug);
                        var prescription = await dc.Set<SysPrescription>()
                            .FirstOrDefaultAsync(e => e.PayId == element.ID && e.Status == SysOrderStatus.退款中);
                        if (prescription != null) prescription.Status = SysOrderStatus.退款完成;
                    }
                    else if (result.Code == 3)
                    {
                        element.RefundStatus = RefundStatusEnum.退款失败;
                        element.UpdateTime = DateTime.Now;
                        var prescription = await dc.Set<SysPrescription>()
                            .FirstOrDefaultAsync(e => e.PayId == element.ID && e.Status == SysOrderStatus.退款中);
                        if (prescription != null) prescription.Status = SysOrderStatus.退款失败;
                        this.Logger($"订单[{element.OutOrderNo}]退款失败", ActionLogTypesEnum.Debug);
                    }
                    else if (result.Code == 2)
                    {
                        if (element.UpdateTime < DateTime.Now.AddMinutes(-5))
                        {
                            element.RefundStatus = RefundStatusEnum.退款异常;
                            element.UpdateTime = DateTime.Now;
                            element.UseMessage = "退款超时, 请人工检查退款状态";
                            this.Logger($"订单[{element.OutOrderNo}]退款超时, 请人工检查退款状态", ActionLogTypesEnum.Exception);
                        }
                    }
                    else
                    {
                        this.Logger($"查询退款结果出错, 请求数据:{result.Request}, 返回数据:{result.Response}", ActionLogTypesEnum.Exception);
                    }
                }
                await dc.SaveChangesAsync();
                return true;

            }
            catch (Exception e)
            {
                this.Logger($"查询退款结果异常{e.Message}, 详细信息:{JsonConvert.SerializeObject(e)}", ActionLogTypesEnum.Exception);
            }
            return false;
        }
    }
}
